<template>
  <!-- 进展及成本 -->
  <div v-loading="loading">
    <el-button type="primary" @click="addItem">添加</el-button>
    <div class="list-box">
      <ProTable
        ref="proTable"
        class="list"
        :columns="columns"
        :data="list"
        row-key="progressId"
        :tool-button="false"
        :pagination="false"
        :height="list.length > 0 ? '' : 200"
      >
        <!-- 是否挂起 -->
        <template #dataFlag="scope">
          <div>{{ scope.row.dataFlag ? "是" : "否" }}</div>
        </template>
        <!-- 开始到结束实际时间 -->
        <template #startToEedTime="scope">
          <div>{{ formatTime(scope.row.startToEedTime) }}</div>
        </template>
        <!-- 实际用时 -->
        <template #actualTime="scope">
          <div>{{ formatTime(scope.row.actualTime) }}</div>
        </template>
        <!-- 状态 -->
        <template #status="scope">
          <div>
            <span v-if="scope.row.status == 1">处理中</span>
            <span v-else-if="scope.row.status == 2">已完成</span>
            <span v-else></span>
          </div>
        </template>
        <!-- 技术员费用 -->
        <template #skillFees="scope">
          <div>￥{{ parseFloat(scope.row.skillFees).toFixed(2) }}</div>
        </template>
        <!-- 物料成本 -->
        <template #materialCost="scope">
          <div>￥{{ parseFloat(scope.row.materialCost).toFixed(2) }}</div>
        </template>
        <!-- 其他费用 -->
        <template #othersFees="scope">
          <div>￥{{ parseFloat(scope.row.othersFees).toFixed(2) }}</div>
        </template>
        <!-- 总费用 -->
        <template #totalFees="scope">
          <div>￥{{ parseFloat(scope.row.totalFees).toFixed(2) }}</div>
        </template>
        <!-- 操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="EditPen" @click="editItem(scope.row)">编辑</el-button>
          <el-button type="danger" link :icon="Delete" @click="deleteItem(scope.row)">删除</el-button>
        </template>
      </ProTable>
    </div>
    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="form.progressId ? '编辑进展及成本' : '新增进展及成本'" width="680px">
      <div style="padding-right: 10px">
        <el-form label-width="170">
          <el-form-item label="技术员" required>
            <div style="display: flex; width: 100%">
              <el-input
                style="flex: 1; overflow: hidden"
                v-model="form.technicianName"
                placeholder="请选择技术员"
                readonly
              ></el-input>
              <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectUser"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="开始/结束时间" required>
            <div style="display: flex; justify-content: space-between; width: 100%">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="YYYY-MM-DD"
                time-format="hh:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
                style="width: 230px"
              />
              <span>-</span>
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="YYYY-MM-DD"
                time-format="hh:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择结束时间"
                style="width: 230px"
              />
            </div>
            <div>预估时间：{{ estimatedTime.minute_text }}</div>
          </el-form-item>
          <!-- <el-form-item label="结束时间" required> </el-form-item> -->
          <!-- <el-form-item label="预估时间">
            <div>{{ estimatedTime.minute_text }}</div>
          </el-form-item> -->
          <el-form-item label="实际处理时间">
            <div style="display: flex; align-items: center">
              <el-input type="number" v-model="form.hour" style="width: 80px"></el-input>
              <span style="margin: 0 10px">小时</span>
              <el-input type="number" v-model="form.minute" style="width: 80px"></el-input>
              <span style="margin-left: 10px">分钟</span>
            </div>
          </el-form-item>
          <el-form-item label="技术员每小时费用(CNY)">
            <el-input v-model="form.perHourFees" readonly></el-input>
          </el-form-item>
          <el-form-item label="技术员费用(CNY)">
            <el-input v-model="skillFees" readonly></el-input>
          </el-form-item>
          <el-form-item label="物料成本(CNY)">
            <el-input v-model="form.materialCost"></el-input>
          </el-form-item>
          <el-form-item label="其他费用(CNY)">
            <el-input v-model="form.othersFees"></el-input>
          </el-form-item>
          <el-form-item label="总费用(CNY)">
            <el-input type="number" v-model="totalFees" readonly></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="form.description" :rows="3"></el-input>
          </el-form-item>
          <el-form-item label="所属阶段">
            <el-input v-model="form.stage"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio :value="1" border>处理中</el-radio>
              <el-radio :value="2" border>已完成</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="任务">
            <div style="display: flex; width: 100%">
              <el-input style="flex: 1; overflow: hidden" v-model="taskName" placeholder="请选择任务" readonly></el-input>
              <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="showSelectTaskMask"></el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择技术员 -->
    <SelectUserMask ref="selectUserMask" title="技术组" @change="selectUserChange"></SelectUserMask>
    <!-- 选择任务 -->
    <el-dialog v-model="selectTaskMask" title="选择关联任务" width="1000px">
      <div class="select-task-mask">
        <ProTable
          :columns="taskColumns"
          :data="taskList"
          :tool-button="false"
          :pagination="false"
          :height="taskList.length > 0 ? '' : 200"
        >
          <template #option="scope">
            <div>
              <el-button @click="selectTaskItem(scope.row)">选择</el-button>
            </div>
          </template>
        </ProTable>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="CostList">
import { ref, reactive, watch, computed } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, EditPen, Search } from "@element-plus/icons-vue";

import ProTable from "@/components/ProTable/index.vue";
import SelectUserMask from "@/components/SelectUserMask/index.vue";
// import TaskListBox from "@/components/TaskListBox/index.vue";

import { findPagerCost, saveCost, editCost, deleteCost } from "@/api/modules/common";
import { findPagerChangeTask } from "@/api/modules/eventManagement";

const props = defineProps({
  eno: Number || String,
  eventType: String,
  pno: String
});

const columns = reactive([
  { prop: "progressId", label: "ID", width: 100, fixed: "left" },
  { prop: "dataFlag", label: "挂起", width: 120 },
  { prop: "fullName", label: "技术员", width: 150 },
  { prop: "startTime", label: "开始时间", width: 180 },
  { prop: "endTime", label: "结束时间", width: 180 },
  { prop: "startToEedTime", label: "开始到结束实际时间", width: 180 },
  { prop: "actualTime", label: "实际处理时间", width: 150 },
  { prop: "skillFees", label: "技术员费用", width: 150 },
  { prop: "materialCost", label: "物料成本", width: 150 },
  { prop: "othersFees", label: "其他费用", width: 150 },
  { prop: "totalFees", label: "总费用", width: 150 },
  { prop: "stage", label: "所属阶段", width: 150 },
  { prop: "status", label: "状态", width: 150 },
  { prop: "operation", label: "操作项", width: 150, fixed: "right" }
]);

const list = ref<any[]>([]);
const loading = ref(true);

const getList = () => {
  if (props.eno) {
    findPagerCost(props.eno, "itsm.change", {
      _search: false,
      nd: new Date().getTime(),
      sidx: "progressId",
      sord: "desc",
      page: 1,
      rows: 20
    })
      .then((res: any) => {
        list.value = res.data;
        loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      });
  } else if (props.pno) {
    findPagerCost(props.pno, "itsm.problem", {
      _search: false,
      nd: new Date().getTime(),
      sidx: "progressId",
      sord: "desc",
      page: 1,
      rows: 20
    })
      .then((res: any) => {
        list.value = res.data;
        loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      });
  } else {
    list.value = [];
  }
};

getList();

watch(
  () => props.eno,
  val => {
    getList();
  }
);
// 格式化时间
const formatTime = time => {
  return Math.floor(time / 60) + "h" + (time % 60) + "m";
};

const dialogVisible = ref(false);
const form = reactive({
  progressId: "", // 进展id
  technicianNo: "", // 技术员id
  technicianName: "", // 技术员名称
  startTime: "", // 开始时间
  endTime: "", // 结束时间
  hour: "", // 实际小时
  minute: "", // 实际分钟
  perHourFees: "0.00", // 技术员时薪
  skillFees: "", // 技术员费用
  materialCost: "", // 物料成本
  othersFees: "", // 其他费用
  totalFees: "", // 总费用
  description: "", // 描述
  stage: "", // 所属阶段
  status: "", // 状态
  taskId: "" // 任务id
});
const taskName = ref("");

const skillFees = computed(() => {
  let price = "0.00";
  if ((form.hour || form.minute) && form.perHourFees) {
    let allMinute = parseInt(form.hour || "0") * 60 + parseInt(form.minute || "0");
    price = ((parseFloat(form.perHourFees) / 60) * allMinute).toFixed(2);
  }
  return price;
});

const totalFees = computed(() => {
  let total = parseFloat(skillFees.value || "0") + parseFloat(form.materialCost || "0") + parseFloat(form.othersFees || "0");
  return total.toFixed(2);
});

// 预估时间
const estimatedTime = computed(() => {
  let left_time = 0; // 分钟
  let text = "0小时0分钟"; // 中文显示
  if (form.startTime && form.endTime) {
    let start = new Date(form.startTime.replace(/-/g, "/")).getTime();
    let end = new Date(form.endTime.replace(/-/g, "/")).getTime();
    left_time = Math.floor((end - start) / 1000 / 60);
    text = Math.floor(left_time / 60) + "小时" + (left_time % 60) + "分钟";
  }
  return {
    minute: left_time, // 分钟
    minute_text: text // 中文显示
  };
});

// 新增
const addItem = () => {
  // todo
  dialogVisible.value = true;
};

// 编辑
const editItem = item => {
  // todo
  dialogVisible.value = true;
};

// 选择技术员弹窗
const selectUserMask = ref();
const selectUser = () => {
  selectUserMask.value?.open();
};
// 选择技术员
const selectUserChange = e => {
  console.log(e);
  form.technicianNo = e.userId;
  form.technicianName = e.fullName;
  form.perHourFees = parseFloat(e.userCost).toFixed(2);
};

// 选择任务弹窗
const selectTaskMask = ref(false);
const showSelectTaskMask = () => {
  selectTaskMask.value = true;
};

const taskColumns = reactive([
  { prop: "taskId", label: "编号", width: 120 },
  { prop: "etitle", label: "标题" },
  { prop: "taskStatus", label: "状态" },
  { prop: "owner", label: "组长" },
  { prop: "option", label: "操作项", width: 120 }
]);

const taskList = ref([]);

findPagerChangeTask({
  "queryDTO.eno": props.eno,
  "hisotryRecordDto.eventType": props.eventType,
  _search: false,
  nd: new Date().getTime(),
  sidx: "taskId",
  sord: "desc",
  page: 1,
  rows: 20
}).then((res: any) => {
  taskList.value = res.data || [];
});
// 选择一个任务
const selectTaskItem = item => {
  form.taskId = item.taskId;
  taskName.value = item.etitle;
  selectTaskMask.value = false;
};

const formLoading = ref(false);

const submit = () => {
  let actualTime = 0; // 实际时间，分钟
  if (form.hour) {
    actualTime += parseInt(form.hour) * 60;
  }
  if (form.minute) {
    actualTime += parseInt(form.minute);
  }
  let data = {
    "costDTO.eno": props.eno,
    "costDTO.eventType": props.eventType,
    "costDTO.userId": form.technicianNo,
    "costDTO.startTime": form.startTime,
    "costDTO.endTime": form.endTime,
    "costDTO.startToEedTime": estimatedTime.value.minute,
    "costDTO.actualTime": actualTime,
    "costDTO.perHourFees": form.perHourFees,
    "costDTO.skillFees": form.skillFees,
    "costDTO.materialCost": form.materialCost,
    "costDTO.othersFees": form.othersFees,
    "costDTO.totalFees": form.totalFees,
    "costDTO.description": form.description,
    "costDTO.stage": form.stage,
    "costDTO.status": form.status,
    "costDTO.taskId": form.taskId // 任务id
  };
  formLoading.value = true;
  if (form.progressId) {
    // 编辑
    data["costDTO.progressId"] = form.progressId;
    editCost(data)
      .then(() => {
        formLoading.value = false;
        ElMessage.success("保存成功");
        dialogVisible.value = false;
        getList();
      })
      .catch(() => {
        formLoading.value = false;
      });
  } else {
    // 新增
    saveCost(data)
      .then(() => {
        formLoading.value = false;
        ElMessage.success("保存成功");
        dialogVisible.value = false;
        getList();
      })
      .catch(() => {
        formLoading.value = false;
      });
  }
};

// 删除
const deleteItem = item => {
  ElMessageBox.confirm("确定要删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // 删除
      loading.value = true;
      deleteCost({
        ids: item.progressId
      })
        .then(() => {
          loading.value = false;
          ElMessage.success("已删除");
          getList();
        })
        .catch(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // todo
    });
};
</script>

<style lang="scss" scoped>
.list-box {
  margin-top: 10px;
  :deep(.card) {
    padding: 0;
    border: none;
  }
}
.flex-1 {
  flex: 1;
  overflow: hidden;
}
.select-task-mask {
  :deep(.card) {
    padding: 0;
    border: none;
  }
}
</style>
